<?php

require_once('Classes/Utils/FileLift/FileLiftCore.inc');

class  FileLiftStorer extends FileLiftCore
{
	private $sessionIndex;
	
	public function __construct($profile)
	{
		parent::__construct($profile, array(), true);
		
		$this->sessionIndex = $this->getSessionIndex();
	}
	
	//
	// PUBLIC METHODS
	//
	
	//ALERT::: DELETE IS NOT CHECKED. DON'T USE IT
	/* deletes a file. 
	 * @filename : name of the file to delete
	 * @cat : categorie of the file. If given, the system will search into the specific directorie instead on tmp directorie
	 * returns true on sucess, false on failture
	 */
	/*public function delete($filename, $cat=false) {
		if($this->setCat($cat))
			$p = $this->find($filename, $this->workCat['path']);
		else
			$p = $this->find($filename);
		
		if($p)
			return $this->del($p);
		return false;
	}*/
	
	
	/* Checks if index have something to relocate 
	 * returns:
	 * false if there is nothing to relocate
	 * array with field names if there is something
	 * */
	private function readIndex() {
		$response = array();
		foreach($this->sessionIndex as $value)
		{
			if($value['status'] == 'stored')
				$response[] = $value['field'];
		}
		if($response)
			return $response;
		return false;
	}
	
	/* Store pending tmp files on session and return the results
	 * Returns array:
	 * keys are field names 
	 * values definitive file names
	 * Returns false if there are no changes 
	 * */
	public function getChanges($id, $cat) {
		//check if there is something to relocate
		$fields = $this->readIndex();
		if(!$fields)
			return false;
		
		//relocate files and create response array
		$response = array();
		$data = $this->relocate($id, $cat);
		if(is_string($data))
			$this->kill($data);
		foreach($fields as $field)
		{
			if($newname = $this->getNewName($field, $data))
				$response[$field] = $newname;
		}
		if($response)
			return $response;
		return false;
	}
	
	/* Returns filename of files relocated (if suceed)
	 * @array: data array returned from $this->relocate() method
	 * @field: field of the file, corresponding to the input file name
	 * returns: 
	 * string with filename
	 * false if field not found  
	 * */
	public function getNewName($field, $array) {
		if(!$array['sucess'])
			return false;
		foreach($array['succeed'] as $key => $value)
		{
			if($value['field'] == $field)
				return $value['filename'];
		}
		return false;
	}
	
	/*
	 * Shorcut to FileLiftCore::find() with extra function:
	 * 		if a category is given it will be set as workCat before doing find()
	 */
	public function find($filename, $category = false) {
		if($category)
			if(  !$this->setCat($category)  )
				return 'Wrong category given';
		return parent::find($filename);
	}
	
	/*	Relocates files from tmp path onto them respectives folders
	 * @identifier: session/user unique identifier wich will be used to rename the files
	 * returns:
	 * false => crash failture, wrong identifier
	 * string 'Index is Empty' => no files to relocate
	 * array => some files sucess (some may had fail, check the response)
	 *	params: @identifier: int or string wich is the session/user unique identifier 
	 */
	public function relocate($identifier, $cat) {
		
		$this->data = array();

		if(!$this->setId($identifier))
			return false;	//Need a identifier to do reposition.
		if($this->conf['privatefolders'])
		{
			if($error = $this->checkMainFolders($identifier, $cat))
				return false;
			//print $error for debugging
		}
			
		if(!$this->sessionIndex)
			return 'Index is Empty';
		
		$fails = array('sucess' => 0, 'fails' => 0, 'ignored' => 0, 'failed' => array());
		foreach($this->sessionIndex as $key => $data)
		{
			//if the file was previusly deleted jump to the next file
			if($data['status'] == 'deleted' || $data['status'] == 'relocated' || $data['status'] == 'failed') {
				$fails['ignored']++;
				continue;
			}
			//get the categorie & basename from the original file
			$name = explode($this->conf['tmp-spliter'], $data['filename']);
			$cat = $name[1];
			$name = $name[2];
			if(!$cat || !$name) {
				$fails['failed'][$fails['fails']] = $data;
				$fails['fails']++; 
				$this->updateIndexEntry($data['filename'], 'failed', 'no cat || no name');
				continue;
			}
			
			//set workCat 
			if(!$this->setCat($cat)) {
				$fails['failed'][$fails['fails']] = $data;
				$fails['fails']++;
				$this->updateIndexEntry($data['filename'], 'failed', 'FileLiftCore::setCat returned error (category does not exist)');
				continue;
			}

			//search the file
			$path = $this->find($data['filename']);
			if(!$path) {
				$fails['failed'][$fails['fails']] = $data;
				$fails['fails']++;
				$this->updateIndexEntry($data['filename'], 'failed', 'FileLiftCore::store returned not found');
				continue;
			}
			
			//store file, save result
			$newname = $this->ren($name, $this->getInfo($path));
			$r = $this->store($path, $this->path . '/' . $newname);
			if($r) {
				$fails['succeed'][$fails['sucess']] = $data;
				$fails['succeed'][$fails['sucess']]['filename'] = $r;
				$fails['sucess']++;
				$this->updateIndexEntry($data['filename'], 'relocated');
			}
			else {
				$fails['failed'][$fails['fails']] = $data;
				$fails['fails']++;
				$this->updateIndexEntry($data['filename'], 'failed', 'FileLiftCore::store returned error');
			}
		}
		return $fails;
	}
	
}
?>